package com.cmf.myproject.net;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;

import org.apache.http.client.HttpClient;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {

    private final static int MAX_CONN_TOTAL = 1000;
    private final static int MAX_CONN_PER_ROUTE = 1000;
    private final static int CONNECT_TIMEOUT = 30 * 1000;
    private final static int READ_TIMEOUT = 30 * 1000;
    
    
    @Bean
    public RestTemplate restTemplate() throws Exception {
    	

        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(createIgnoreVerifySSL(),NoopHostnameVerifier.INSTANCE);
    	
        HttpClient httpClient = HttpClientBuilder.create()
        		.setMaxConnTotal(MAX_CONN_TOTAL)
        		.setMaxConnPerRoute(MAX_CONN_PER_ROUTE)
        		.setSSLSocketFactory(sslSocketFactory)
        		.build();
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
        factory.setConnectTimeout(CONNECT_TIMEOUT);
        factory.setReadTimeout(READ_TIMEOUT);

        RestTemplate restTemplate = new RestTemplate(factory);
        restTemplate.setErrorHandler(new ResponseErrorHandler() {
			
			@Override
			public boolean hasError(ClientHttpResponse response) throws IOException {
				return false;
			}
			
			@Override
			public void handleError(ClientHttpResponse response) throws IOException {
				
			}
		});
        
        return restTemplate;
    }

    
    public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {  
    	SSLContextBuilder builder = new SSLContextBuilder();
    	try {
			builder.loadTrustMaterial(null, new TrustStrategy() {
			    @Override
			    public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
			        return true;
			    }
			});
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
        return builder.build();  
    }

}
